//
//  MBDPostListViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/3/19.
//

import Foundation
import UIKit
import YYText
import SwiftyJSON
import MJRefresh
import Toast_Swift

class MBDPostListViewController : MBDBaseViewController {
    var tableView: UITableView!
    var viewModel : MBDPostListViewModel!
    var pageIndex : Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我创建的"
        viewModel = MBDPostListViewModel()
        pageIndex = 1

        tableView = UITableView()
                
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            [unowned self] in
            self.pageIndex = 1

            viewModel.doRequest { error,result,totalPage in
                                
                if nil != error {
                    self.view.makeToast(error?.localizedDescription,position: .center)
                } else {
                    self.viewModel.cellModels = result
                    self.tableView.reloadData()
                    self.tableView.mj_header?.endRefreshing()
                    if self.pageIndex >= totalPage {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.resetNoMoreData()
                    }
                }
            }
            
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            [unowned self] in
            self.pageIndex += 1
            viewModel.doRequest(pageNum: self.pageIndex,completion: { error,result,totalPage in
                
                var cellModels = Array<MBDPostCellModel>()
                cellModels.append(contentsOf: self.viewModel.cellModels ?? Array<MBDPostCellModel>())
                if result?.count ?? 0 > 0 {
                    cellModels.append(contentsOf: result!)
                }
                self.viewModel.cellModels = cellModels
                
                self.tableView.reloadData()
                self.tableView.mj_header?.endRefreshing()
                
                if self.pageIndex >= totalPage {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }
            })
            
            self.tableView.mj_footer?.endRefreshing()
        })
        
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.allowsMultipleSelection = false
        tableView.allowsSelectionDuringEditing = false
        tableView.allowsMultipleSelectionDuringEditing = false
        self.view.addSubview(tableView)
        
        NSLayoutConstraint.activate([
        self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: tableView.topAnchor),
                    self.view.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
                    self.view.leadingAnchor.constraint(equalTo: tableView.leadingAnchor),
                    self.view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
                ])
        tableView.backgroundColor = UIColor(colorHex: 0xF4F4F4)
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.rowHeight = 100
        
        tableView.register(MBDPostCell.self, forCellReuseIdentifier: "MBDPostCell")
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshUI()

    }
    
    override func updateColors() {
        tableView.setDynamicBackgroundColor()        
        
        // 遍历并更新 cellModels
        if let cellModels = self.viewModel.cellModels {
            for i in 0..<cellModels.count {
                let updatedGroupDetail = cellModels[i].groupDetail
                
                // 重新设置 groupDetail
                self.viewModel.cellModels?[i].groupDetail = updatedGroupDetail
            }
        }
        
        self.tableView.reloadData()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        if traitCollection.userInterfaceStyle == .dark {
            return .lightContent  // 暗黑模式下，状态栏文字为白色
        } else {
            if #available(iOS 13.0, *) {
                return .darkContent
            } else {
                // Fallback on earlier versions
                return .default
            }   // 浅色模式下，状态栏文字为黑色 (iOS 13 及之后)
            
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        return false
    }
}


extension MBDPostListViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let count = self.viewModel.cellModels?.count ?? 0
        return count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "MBDPostCell", for: indexPath)
        (cell as! MBDPostCell ).cellModel = cellModel
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let realCellModel = cellModel as! MBDPostCellModel
        let groupId = realCellModel.groupDetail!.groupId
        let vc = UIAlertController(title: nil, message: "确定删除？", preferredStyle: UIAlertController.Style.alert)
        let confirmAction = UIAlertAction(title: "确认", style: UIAlertAction.Style.default) { UIAlertAction in
            
            if let gId = groupId {
                self.viewModel.deleteGroupRequest(groupId: gId, completion: { result in
                    self.refreshUI()
                })
            }
            
            
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel)
        vc.addAction(cancelAction)
        vc.addAction(confirmAction)
        self.present(vc, animated: true)
        
//        let indexPathTemp = IndexPath(index: indexPath.row)
//
//        self.tableView .deleteRows(at: [indexPathTemp], with: UITableView.RowAnimation.automatic)
    }
    
    func refreshUI(){
        self.pageIndex = 1
        viewModel.doRequest { error,result,totalPage in
            
            if nil != error {
                self.view.makeToast(error?.localizedDescription,position: .center)
            } else {
                self.viewModel.cellModels = result
                self.tableView.reloadData()
                self.tableView.mj_header?.endRefreshing()
                
                if(0 == result?.count) {
                    self.tableView.setEmptyView(title: "您尚未发布任何群组",
                                                       message: "赶紧去发布吧")
                } else {
                    self.tableView.restore()
                }
                
                if totalPage == 1 {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self.tableView.mj_footer?.resetNoMoreData()
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        return (cellModel as! MBDPostCellModel).cellHeight
    }
    
}


extension MBDPostListViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let viewModel = MBDUploadGroupViewModel(groupDetail: cellModel.groupDetail,isUpdate: true)
        let modifyVC = MBDUploadGroupViewController(viewModel: viewModel)
        self.navigationController?.pushViewController(modifyVC, animated: true)
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
}
